class Car < ApplicationRecord
    belongs_to :user
    belongs_to :restaurant
    has_many :order_items,dependent: :destroy

  def add_line_item_from_order(order)
      order.order_items.each do |item|
          item.order_id = nil
          item.car_id = self.id
          item.save
      end
  end  

  def clear_all
    order_items.destroy_all
  end  

  def add_food(food_id)
    current_item = order_items.find_by(food_id:food_id)
    if current_item
      current_item.quantity += 1
    else
      current_item = order_items.build(food_id:food_id)     
    end
    current_item.save
    
  end

  def subtract_food(food_id)
    current_item = order_items.find_by(food_id:food_id)
    if current_item.present?
        current_item.quantity -= 1
        if current_item.quantity == 0
            current_item.destroy
            return
        end    
        current_item.save
    end    
  end  

  def car_total_price
     order_items.to_a.sum{|item| item.total_price}
  end  

end
